<template>
  <div>
    <Row class="margin-bottom-20" type="flex" justify="space-between" align="middle" :gutter="20">

      <i-col span="5">
        <Select
          ref="province"
          @on-open-change="visible => this.handleAddressClose(visible, 'provinceId', 'province')"
          clearable filterable placeholder="省份/直辖市/自治区" v-model="provinceId" @on-change="selectProvince" :label-in-value="true">
          <Option v-for="item in provinces" :value="item.id +'$' +item.region_code" :key="item.id">{{ item.short_name }}</Option>
        </Select>
      </i-col>

      <i-col span="5">
        <Select
          ref="city"
          @on-open-change="visible => this.handleAddressClose(visible, 'cityId', 'city')"
          clearable filterable placeholder="城市" v-model="cityId" @on-change="selectCity" :label-in-value="true">
          <Option v-for="item in cities" :value="item.id +'$' +item.region_code" :key="item.id">{{ item.short_name }}</Option>
        </Select>
      </i-col>

      <i-col span="5">
        <Select
          ref="district"
          @on-open-change="visible => this.handleAddressClose(visible, 'districtId', 'district')"
          clearable filterable placeholder="区域" v-model="districtId" @on-change="selectDistrict" :label-in-value="true">
          <Option v-for="item in districts" :value="item.id +'$' +item.region_code" :key="item.id">{{ item.short_name }}</Option>
        </Select>
      </i-col>

      <i-col span="9">
        <Tooltip content="输入地址搜索时请勿加省/市/区" placement="top-start" class="ivu-tip-block">
          <Input
            icon="ios-search-strong"
            v-model.trim="keywords"
            placeholder="关键字：房源地址/小区/房源编号"
            @on-click="search"
            @keydown.enter.native="search"
          />
        </Tooltip>
      </i-col>

    </Row>

    <Row :gutter="20" class="margin-bottom-20">
      <i-col span="5">
        <Select
          clearable
          placeholder="公寓类型"
          @on-change="selectHomeType">
          <Option :value="0">全部</Option>
          <Option :value="1">分散式</Option>
          <Option :value="2">集中式</Option>
        </Select>
      </i-col>
      <i-col span="5">
        <BranchSelector show-head="!userHasBranchs" @on-change="selectStore"/>
      </i-col>
    </Row>

	</div>
</template>

<script>
import { HomeTypeEnum } from '@/libs/const'
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'
import BranchSelector from '@/components/selector/branch-selector'

let _searchParams = {
  province: null,
  city: null,
  district: null,
  // branch_ids: null,
  // home_types: null,
  keyword: null,
  offset: 0
}

export default {
  components: {
    BranchSelector
  },
  data () {
    return {
      HomeTypeEnum: HomeTypeEnum,

      provinces: null,
      cities: null,
      districts: null,
      stores: null,
      collapseVisible: false,
      housekeepers: [],

      selectedProvince: null,
      provinceId: null,
      cityId: null,
      districtId: null,
      selectedCity: null,
      selectedDistrict: null,
      selectedKeeper: null,
      // selectedStores: [],
      // selectedHomeTypes: null,

      selectedHomeType: 0,
      selectedStore: null,

      keywords: null,
      storeDefaultCnt: 15,
      isStoreOpened: false
    }
  },

  created () {
    if (this.$route.query.input) {
      this.keywords = this.$route.query.input
    }
    if (this.$route.query.radio) {
      this.selectedStore = +this.$route.query.radio
      this.selectStore(this.selectedStore)
    }

    dataCenter.getProvinces(this, res => {
      this.provinces = res
    })

    dataCenter.getStores(this, res => {
      this.stores = res

      this.$nextTick(() => {
        let height = this.$refs.stores && this.$refs.stores.offsetHeight
        // util.log('stores height', height);
        if (height > 60) {
          this.collapseVisible = true
        }
      })
    })

    // this.fetchHousekeeper()
  },

  computed: {
    userHasBranchs () {
      const { branches } = this.$store.state.user
      return !!branches.length
    }
  },
  methods: {
    handleAddressClose (visible, field, ref) {
      if (!visible && !this[field] && this.$refs[ref]) {
        this.$refs[ref].setQuery(null)
      }
    },
    fetchHousekeeper () {
      const query = {
        offset: 0,
        limit: 100,
        role_id: 104,
        list_type: 'page'
      }
      http.request(this, api.user_list, null, query, (res, err) => {
        if (err) {
          this.$Message.error('获取管家列表失败')
        } else {
          this.housekeepers = res.rows
        }
      })
    },
    selectProvince (data) {
      this.selectedProvince = data
      this.cities = []
      this.selectedCity = null
      this.selectedDistrict = null
      this.cityId = null
      this.districtId = null

      if (data && data.value) {
        // tag 取region_code前2位
        data.tag = data.value.split('$')[1]
        data.value = data.value.split('$')[0]
        dataCenter.getCities(this, data.value, res => {
          this.cities = this.cities.concat(res)
        })
      }
    },

    selectCity (data) {
      this.selectedCity = data
      this.selectedDistrict = null
      this.districtId = null
      if (data && data.value) {
        // tag 取region_code 3-4位
        data.tag = data.value.split('$')[1]
        // util.log(data.tag)
        data.value = data.value.split('$')[0]
        dataCenter.getDistricts(this, data.value, res => {
          this.districts = res
        })
      } else {
        this.districts = null
      }
    },

    selectDistrict (data) {
      // tag 取region_code 5-6位
      if (data && data.value) {
        data.tag = data.value.split('$')[1]
        data.value = data.value.split('$')[0]
        this.selectedDistrict = data
      } else {
        this.selectedDistrict = null
      }
    },

    // selectHomeTypes(data) {
    //     this.selectedHomeTypes = data;
    // },

    selectHomeType (type) {
      this.selectedHomeType = type

      // let homeTypes = [];
      // if (this.selectedHomeType == 0) {
      //     homeTypes.push(HomeTypeEnum.DECENTRALIZED);
      //     homeTypes.push(HomeTypeEnum.CENTRALIZED);
      // } else {
      //     homeTypes.push(this.selectedHomeType);
      // }
      this.$emit('on-filter-home-type', this.selectedHomeType === 0 ? '' : this.selectedHomeType)
    },

    selectStore (id) {
      this.selectedStore = id
      let branchId = this.selectedStore ? this.selectedStore : null
      if (this.selectedStore === 0) {
        branchId = 0
      }
      this.$emit('on-filter-store', branchId)
    },

    selectKeeper (id) {
      this.selectedKeeper = id
    },

    calcTextLen (str) {
      return util.calcTextLen(str)
    },

    collapse (isOpen) {
      this.isStoreOpened = !this.isStoreOpened
    },

    search () {
      const provinceTag = this.selectedProvince && this.selectedProvince.value ? this.selectedProvince.tag : ''
      const cityTag = this.selectedCity && this.selectedCity.value ? this.selectedCity.tag : ''
      const districtTag = this.selectedDistrict && this.selectedDistrict.value ? this.selectedDistrict.tag : ''
      // util.log(provinceTag, cityTag, districtTag)
      _searchParams.tag = districtTag || cityTag || provinceTag || null
      _searchParams.keyword = this.keywords
      _searchParams.offset = 0

      this.$emit('on-search', _searchParams)
    }
  }
}
</script>

<style lang="less" scoped>
.search {
    &-home-types {
        display: flex;
        align-items: center;
        font-size: 12px;
        padding: 8px 0 0;
    }

    &-store-btn {
        width: 100%;
        cursor: pointer;
        color: #dddee1;
    }
}

.filter-wrap {
    display: flex;
    border: 1px solid #efeff1;
    border-radius: 6px;
    margin: 10px 0 0 0;
    padding: 10px 10px 0;
    overflow: hidden;
    // background-color: #efeff1;
    position: relative;
}
.filter-wrap-top {
    border-bottom: 0;
    border-bottom-right-radius: 0;
    border-bottom-left-radius: 0;
}
.filter-wrap-bottom {
    margin-top: 0;
    padding-top: 0;
    border-top: 0;
    border-top-right-radius: 0;
    border-top-left-radius: 0;
}
.filter-wrap-h {
    max-height: 110px;
}
.home-types-wrap {
    display: flex;
    align-items: center;
    // margin-bottom: 5px;
}
.stores-wrap {
    display: flex;
    padding-right: 100px;
}
.filter-item-label,
.filter-item {
    display: inline-block;
    width: 100px;
    min-width: 100px;
    margin-bottom: 15px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.filter-item-label {
    text-align: center;
}
.icon-collapse-wrap {
    position: absolute;
    top: 44px;
    right: 4px;
    min-width: 100px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    align-items: center;
}
.icon-collapse {
    cursor: pointer;
    color: #05bac5;
    font-size: 24px;
    transition: transform 0.3s;
    &.is-open {
        transform: rotate(180deg);
    }
}
</style>
